package com.huifaapp.mall.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.huifaapp.mall.R;

import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.api.ObserverCallback;
import com.huifaapp.mall.base.activity.BaseActivity;
import com.huifaapp.mall.base.basemvp.IPresenter;
import com.huifaapp.mall.base.bean.BaseBean;
import com.huifaapp.mall.bean.BaseBeans;
import com.huifaapp.mall.bean.LoginBean;
import com.huifaapp.mall.bean.UserBean;
import com.huifaapp.mall.dialogs.LoadingDialog;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.JPushUitil;
import com.huifaapp.mall.view.ClickImageView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * @author: wangZ
 * @date：2017/8/17 16:51
 * FileName：LoginActivity
 * @description：描述登录页面
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener{
    private String mOpenid;

    private String mUnionId;
    private String mName;
    private String mAvatr;
    private TextView tv_SMS_quick_login;
    private TextView tv_Forgot_password_login;
    private TextView tv_login_Register;



    private EditText et_Login_phone;
    private EditText et_login_pwd;
    private TextView tv_login;
    private ClickImageView tv_qq_login;
//    private ImageView image;
    boolean eyeOpen = false ;


    private ImageView iv_login_back;
    private ImageView iv_login_colse;
    private String vipin="";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initData(Bundle bundle) {
        tv_SMS_quick_login= (TextView) findViewById(R.id.tv_SMS_quick_login);
        tv_SMS_quick_login.setOnClickListener(this);
        tv_Forgot_password_login= (TextView) findViewById(R.id.tv_Forgot_password_login);
        tv_Forgot_password_login.setOnClickListener(this);
        tv_login_Register= (TextView) findViewById(R.id.tv_login_Register);
        tv_login_Register.setOnClickListener(this);
//        image= (ImageView) findViewById(R.id.image_login);

        et_Login_phone= (EditText) findViewById(R.id.et_Login_phone);
        String phone=getIntent().getStringExtra("phone");

        if("".equals(phone)){

        }else{
            et_Login_phone.setText(phone);
        }
        et_login_pwd= (EditText) findViewById(R.id.et_login_pwd);
        tv_qq_login= (ClickImageView) findViewById(R.id.tv_qq_login);
        tv_qq_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(LoginActivity.this,MainFragment.class);
                startActivity(intent);
                finish();
            }
        });
        tv_login= (TextView) findViewById(R.id.tv_login_l);
        tv_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoadLogin();
            }
        });
        iv_login_back= (ImageView) findViewById(R.id.iv_login_back);
        iv_login_colse= (ImageView) findViewById(R.id.iv_login_colse);
        iv_login_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        iv_login_colse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                String shopcart="";
//                shopcart=getIntent().getStringExtra("shopcart");
//
//                if("red".equals(shopcart)){
//                    finish();
//                    Intent intent=new Intent(LoginActivity.e)
//                }
                finish();
            }
        });
//        image.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if ( eyeOpen ){
//                    //密码 TYPE_CLASS_TEXT 和 TYPE_TEXT_VARIATION_PASSWORD 必须一起使用
//                    et_login_pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
//                    image.setImageResource( R.drawable.login_icon_bukejian );
//                    eyeOpen = false ;
//                }else {
//                    //明文
//                    et_login_pwd.setInputType( InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD );
//                    image.setImageResource( R.drawable.login_icon_kejian );
//                    eyeOpen = true ;
//                }
//            }
//        });

//      setTtle("登录");
        RxPermissions rxPermissions = new RxPermissions(this); //这里是一个Activity实例
        rxPermissions.requestEach(Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        ).subscribe(new Consumer<Permission>() {
            @Override
            public void accept(Permission permission) throws Exception {

            }
        });
//
//                        subscribe(granted -> {
//                    if (granted) { // 在android 6.0之前会默认返回true
//                        // 已经获取权限
//                    } else {
//                        // 未获取权限
//                    }
//                });

    }

    private void LoadLogin(){

        String phone=et_Login_phone.getText().toString();
        String pwd=et_login_pwd.getText().toString();
        if(phone.equals("")){
            Toast.makeText(LoginActivity.this,"",Toast.LENGTH_SHORT).show();
        }else if(pwd.equals("")){
            Toast.makeText(LoginActivity.this,"",Toast.LENGTH_SHORT).show();
        }
        Log.e("","WYBS"+AUniqueIdentifier.getDeviceId(LoginActivity.this));
        String url = ApiManager.LOGIN_IN+"?phone="+phone+"&pwd="+pwd+"&appId="+ AUniqueIdentifier.getDeviceId(LoginActivity.this);
        Log.e("","登录url===="+url);
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, url, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                LoginBean list = gson.fromJson(responseInfo.result, LoginBean.class);
                if(list.getCode().equals("10000")) {
                    if (list != null && !TextUtils.isEmpty(list.getData().getToken())) {
                        SPUtils.getInstance().put(SPConstants.KEY_USER_TOKEN, list.getData().getToken());
                        SPUtils.getInstance().put(SPConstants.KEY_ISSTORE,list.getIsStore());
                        SPUtils.getInstance().put(SPConstants.KEY_USERID,list.getData().getUserid());
                    }

                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    Log.e("",""+SPUtils.getInstance().getString(SPConstants.KEY_USERID));
//                    Intent intent=new Intent(LoginActivity.this,MainFragment.class);
//                    startActivity(intent);

                    finish();
                }else {
                    SPUtils.getInstance().put(SPConstants.KEY_ISSTORE,list.getIsStore());
                    Toast.makeText(LoginActivity.this, list.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }


            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(LoginActivity.this,"失败",Toast.LENGTH_SHORT).show();
            }
        });
    }
    @Override
    protected void initViews(Bundle savedInstanceState) {

    }


    @Override
    protected IPresenter onLoadPresenter() {
        return null;
    }


    @OnClick({R.id.tv_wx_login, R.id.textView4, R.id.tv_youke})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_wx_login:

//                Bundle bundle = new Bundle();
////              bundle.putString(WebActivity.KEY_TOKEN,resp.getAccessToken());
//                bundle.putString(WebActivity.KEY_URL, Constants.KEY_HOMME_URL);
////                                bundle.putString(WebActivity.KEY_URL,"http://192.168.199.200:3000/eastsRetreat/html/setup.html");
////                                bundle.putString(WebActivity.KEY_URL,"file:///android_asset/js_interaction/hello.html");
//                gotoActivity(WebActivity.class,false,bundle);

                sanLogin();
                break;
            case R.id.tv_youke:
                gotoActivity(WebActivity.class);
                break;
            case R.id.textView4:
                ApiManager.getInstance()
                        .getApiServer()
                        .listRepos("haha")
                        .subscribe(new ObserverCallback<BaseBean<String>>() {
                            @Override
                            protected void onSuccessful(BaseBean<String> resp) {

                            }

                            @Override
                            protected void onError(String code, String errMsg) {

                            }
                        });
                ApiManager.getInstance()
                        .getApiServer()
                        .getWXP("http://www.baidu.com", "haha")
                        .subscribe(new ObserverCallback<BaseBean<String>>() {
                            @Override
                            protected void onSuccessful(BaseBean<String> resp) {

                            }

                            @Override
                            protected void onError(String code, String errMsg) {

                            }
                        });
                ApiManager.getInstance()
                        .getApiServer()
                        .getWX("wang", "haha")
                        .subscribe(new ObserverCallback<BaseBean<String>>() {
                            @Override
                            protected void onSuccessful(BaseBean<String> resp) {

                            }

                            @Override
                            protected void onError(String code, String errMsg) {

                            }
                        });

//            new AlipayUtils(this).getAlipaySignature("0d7ed0db14c440f193c401dab5e30218");

//                ShareDialog shareDialog = new ShareDialog(this);
//
//                final UMWeb web = new UMWeb("http://www.jianshu.com/");
//                web.setTitle("友惠家商城");//标题
//                web.setThumb(new UMImage(this, R.drawable.ic_launcher));  //缩略图
//                web.setDescription("友惠家商城");//描述
//                shareDialog.setWeb(web)
//                        .setShaerListener(new ShareDialog.onShaerListener() {
//                            @Override
//                             public void onCancelu(String name) {
//                                ToastUtils.showShortSafe(name+"分享成功!");
//
//                            }
//
//                            @Override
//                            public void onErro(String name) {
//                                ToastUtils.showShortSafe(name+"分享失败!");
//                            }
//
//                            @Override
//                            public void onComplete(String name) {
//                                ToastUtils.showShortSafe(name+"分享取消!");
//
//                            }
//                        });
//                shareDialog.show();
                break;
        }
    }


    LoadingDialog dialog;

    private void sanLogin() {


        if (dialog == null) {
            dialog = new LoadingDialog(this);
        }
        dialog.setContent("登录中");

        UMAuthListener umAuthListener = new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA platform) {
                //授权开始的回调
                dialog.show();
            }

            @Override
            public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                mUnionId = data.get("unionid");
                mName = data.get("name");
                mAvatr = data.get("iconurl");
                SPUtils.getInstance().put(SPConstants.UNIONID,mUnionId);
                SPUtils.getInstance().put(SPConstants.NAME,mName);
                SPUtils.getInstance().put(SPConstants.MAVATR,mAvatr);

                login(mUnionId,AUniqueIdentifier.getDeviceId(LoginActivity.this), mAvatr, mName);
            }

            @Override
            public void onError(SHARE_MEDIA platform, int action, Throwable t) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                ToastUtils.showShortSafe("微信登录失败!");
            }

            @Override
            public void onCancel(SHARE_MEDIA platform, int action) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                ToastUtils.showShortSafe("微信登录取消!");

            }
        };
        UMShareAPI mShareAPI = UMShareAPI.get(this);
        mShareAPI.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, umAuthListener);
    }


    private void login(final String unionId, String appid, final String avatr, final String name) {
        String url = ApiManager.LOGIN_IN+"?unionid="+unionId+"&appId="+appid;//+"&userHeadImg="+ avatr+"&userNickName="+name;
        Log.e("","登录url===="+url);
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, url, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                LoginBean list = gson.fromJson(responseInfo.result, LoginBean.class);
                if(list.getCode().equals("10000")) {
                    if (list != null && !TextUtils.isEmpty(list.getData().getToken())) {
                        SPUtils.getInstance().put(SPConstants.KEY_USER_TOKEN, list.getData().getToken());
                        SPUtils.getInstance().put(SPConstants.KEY_ISSTORE,list.getIsStore());
                        SPUtils.getInstance().put(SPConstants.KEY_USERID,list.getData().getUserid());
                    }
                    //设置极光生效
                    JPushUitil.getInstance().setJPushTagState(list.getData().getUserid());
                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    Log.e("",""+SPUtils.getInstance().getString(SPConstants.KEY_USERID));
//                    Intent intent=new Intent(LoginActivity.this,MainFragment.class);
//                    startActivity(intent);
                    finish();
                }else if(list.getCode().equals("10021")){
                    Intent intent=new Intent(LoginActivity.this,RegisterLoginActivity.class);
                    intent.putExtra("userNickName",name);
                    intent.putExtra("userHeadImg",avatr);
                    intent.putExtra("unionid",unionId);
                    startActivity(intent);
                    finish();
                }else {
                    Toast.makeText(LoginActivity.this, list.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }


            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(LoginActivity.this,s,Toast.LENGTH_SHORT).show();
            }
        });
//        ApiManager
//                .getInstance()
//                .getApiServer()
//                .login(unionId,appid, avatr, name)
//                .compose(ApiManager.<UserBean>handlResult())
//                .subscribe(new ObserverCallback<UserBean>(this, true, "登录中") {
//                    @Override
//                    protected void onSuccessful(UserBean resp) {
//                        if (resp != null && !TextUtils.isEmpty(resp.getToken())) {
//                            SPUtils.getInstance().put(SPConstants.KEY_USER_TOKEN, resp.getToken());
//
//                        }
////                                ToastUtils.showShortSafe("成功");
//                        LogUtils.e(TAG, resp.toString());
////                        Bundle bundle = new Bundle();
////                        bundle.putString(WebActivity.KEY_TOKEN, resp.getAccessToken());
////                        bundle.putString(WebActivity.KEY_URL, ApiManager.BASE_HTML_URL + JSConstants.HTML_HOME);
//////                                bundle.putString(WebActivity.KEY_URL,"http://192.168.199.200:3000/eastsRetreat/html/setup.html");
//////                                bundle.putString(WebActivity.KEY_URL,"file:///android_asset/js_interaction/hello.html");
//                        //设置极光生效
//                        JPushUitil.getInstance().setJPushTagState(resp.getUserid());
//                        Intent intent=new Intent(LoginActivity.this,MainFragment.class);
//                        startActivity(intent);
////                        gotoActivity(WebActivity.class, false, bundle);
//                    }
//
//                    @Override
//                    protected void onError(String code, String errMsg) {
//                        ToastUtils.showShortSafe(errMsg);
////                        Bundle bundle = new Bundle();
////                        bundle.putString(InputInviteCodeActivity.KEY_OPEN_ID,mOpenid);
////                        bundle.putString(InputInviteCodeActivity.KEY_UNION_ID,mUnionId);
////                        gotoActivity(InputInviteCodeActivity.class,true,bundle);
//                    }
//                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_SMS_quick_login:
                Intent intentsms=new Intent(LoginActivity.this,SMSQuickLoginActivity.class);
                startActivity(intentsms);
                break;
            case R.id.tv_Forgot_password_login:
                Intent intentpass=new Intent(LoginActivity.this,ForgotPasswordLoginActivity.class);
                startActivity(intentpass);
                break;
            case R.id.tv_login_Register:
                Intent intenregister=new Intent(LoginActivity.this,RegisterLoginActivity.class);
                startActivity(intenregister);
                finish();
                break;
        }
    }
}

